package com.weixiao.controller;

import com.alibaba.excel.EasyExcel;
import com.weixiao.entity.User;
import com.weixiao.listener.MemberExcelListener;
import com.weixiao.service.EasyExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * author 韩诚
 * date 2022/12/13
 */
@RestController
@RequestMapping("import")
public class EasyExcelController {
    @Autowired
    private EasyExcelService easyExcelService;

    /**
     * 从Excel导入会员列表
     */
    @PostMapping ( "/import1")
    public void importMemberList1(MultipartFile file) throws IOException {
        //同步读取，将解析结果返回，比如返回List<User>，业务再进行相应的数据集中处理
        List<User> list = EasyExcel.read(file.getInputStream())
                .head(User.class)
                .sheet()
                .doReadSync();
        //遍历打印到控制台
        for (User user : list) {
            System.out.println(user);
        }
    }

    /**
     * 基于Listener方式从Excel导入会员列表
     */
    @PostMapping(value = "/import2")
    public void importMemberList2(MultipartFile file) throws IOException {
        // 不进行结果返回，在MemberExcelListener中进行一条条数据的处理；
        EasyExcel.read(file.getInputStream(), User.class, new MemberExcelListener()).sheet().doRead();
    }

    /**
     * 导出会员列表（下载）
     */
    @RequestMapping("/export1")
    public void exportMembers1(HttpServletResponse response) throws IOException {
        //获取数据
        List<User> userList = easyExcelService.getUserAll();
        System.out.println(userList);

        // 设置文本内省
        response.setContentType("application/vnd.ms-excel");
        // 设置字符编码
        response.setCharacterEncoding("utf-8");
        // 设置响应头
        response.setHeader("Content-disposition", "attachment;filename=user.xlsx");
        //将数据存入Excel表中并下载
        EasyExcel.write(response.getOutputStream(), User.class).sheet("用户列表").doWrite(userList);
    }
}
